package com.example.forum.controller;

import com.example.forum.common.AppResult;
import com.example.forum.common.ResultCode;
import com.example.forum.config.AppConfig;
import com.example.forum.model.Article;
import com.example.forum.model.Board;
import com.example.forum.model.User;
import com.example.forum.services.IArticleService;
import com.example.forum.services.IBoradService;
import com.example.forum.utils.StringUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@RestController
@RequestMapping("article")
@Slf4j
@Api(tags = "文章接口")
public class ArticleController{

    @Resource
    private IArticleService articleService;

    @Resource
    private IBoradService boradService;

    @PostMapping("/create")
    @ApiOperation("发布帖子")
    public AppResult create(HttpServletRequest request , @ApiParam("板块id")@RequestParam("boardId")@NonNull Long boardId
            , @ApiParam("文章标题")@RequestParam("title")@NonNull String title
            , @ApiParam("文章正文")@RequestParam("content")@NonNull String content) {
        // 用户已经登录 -- 登录拦截器
        // 校验用户是否禁言
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            // 当前用户处于禁言状态
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }

        // 判断板块是否存在
        Board board = boradService.selectById(boardId);
        if (board == null || board.getDeleteState() == 1 || board.getState() == 1) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString() + " + boardId = " + boardId);
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);

        }
        // 判断文章标题和内容
        if (StringUtil.isEmpty(title) || StringUtil.isEmpty(content)) {
            log.warn(ResultCode.FAILED_CREATE.toString());
            return AppResult.failed(ResultCode.FAILED_CREATE);
        }

        // 用户创建文章
        Article article = new Article();
        article.setTitle(title);
        article.setContent(content);
        article.setUserId(user.getId());
        article.setBoardId(boardId);
        articleService.create(article);
        return AppResult.success("发布帖子成功");
    }

    /**
     * 根据板块id获取文章
     * @param boardId  版块id 非空 返回对应版块的文章 <br/> 空 返回所有的文章
     * @return  文章列表
     */
    @GetMapping("/getAllByBoardId")
    @ApiOperation("根据板块id获取文章")
    public AppResult<List<Article>> getAllByBoardId (@ApiParam("版块id")@RequestParam(value = "boardId" ,required = false)  Long boardId) {
        List<Article> articles = null;
        if (boardId == null) {
            articles = articleService.selectAll();
        } else {
            if (boardId <= 0) {
                return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
            }
            articles = articleService.selectAllByBoardId(boardId);
        }
        if (articles == null) {
            articles = new ArrayList<>();
        }
        return AppResult.success(articles);

    }

    @ApiOperation("根据文章id查询文章")
    @GetMapping("/details")
    public AppResult<Article>  getDetails(HttpServletRequest request ,
            @ApiParam("文章id")@RequestParam("id")@NonNull Long id) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        Article article = articleService.selectDetailById(id);

        if (article == null) {
            log.warn(ResultCode.FAILED_PARAMS_VALIDATE.toString() + " + 文章id = " + id);
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        if (user.getId() == article.getUserId()) {
            article.setOwn(true);
        }
        return AppResult.success(article) ;
    }


    @ApiOperation("修改文章")
    @PostMapping("/modify")
    public AppResult modify(HttpServletRequest request ,@ApiParam("文章id") @NonNull @RequestParam("id") Long id
            ,@ApiParam("文章标题") @NonNull @RequestParam("title") String title
            ,@ApiParam("文章内容") @NonNull @RequestParam("content") String content) {
        if (StringUtil.isEmpty(title) || StringUtil.isEmpty(content)) {
            return AppResult.failed(ResultCode.FAILED_PARAMS_VALIDATE);
        }
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        // 判断用户状态  state 1 禁言
         if (user.getState() == 1) {
             log.warn(ResultCode.FAILED_USER_BANNED.toString());
             return AppResult.failed(ResultCode.FAILED_USER_BANNED);
         }
        // 判断文章是否存在
        Article article = articleService.selectById(id);
         if (article == null || article.getDeleteState() == 1) {
             // 文章已经被删除
             log.warn(ResultCode.FAILED_NOT_EXISTS.toString());
             return AppResult.failed(ResultCode.FAILED_NOT_EXISTS);
         }
        // 判断是否是作者
        if (user.getId() != article.getUserId()) {
            log.warn(ResultCode.FAILED_FORBIDDEN.toString());
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        articleService.modify(id,title,content);
        log.info("更新成功");
        return AppResult.success(ResultCode.SUCCESS);
    }

    @ApiOperation("点赞操作")
    @PostMapping("/thumbsUp")
    public AppResult thumbsUp(HttpServletRequest request ,@ApiParam("文章id")@RequestParam("id")@NonNull Long id) {
        //判断用户状态
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getState() == 1) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 点赞
        articleService.thumbsUpById(id);
        return AppResult.success();
    }

    /**
     * 根据Id删除帖⼦
     *
     * @param id 帖⼦Id
     * @return
     */
    @ApiOperation("删除帖⼦")
    @PostMapping("/delete")
    public AppResult deleteById(HttpServletRequest request ,@ApiParam("文章id")@RequestParam("id")@NonNull Long id) {
        // 判断用户是否存在 是不是被删除
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (user.getDeleteState() == 1) {
            // 用户被删除
            log.warn(ResultCode.FAILED_USER_BANNED.toString());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        // 文章是否存在
        Article article = articleService.selectById(id);
        if (article == null || article.getDeleteState() == 1) {
            //文章不存在 , 无法删除
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_NOT_EXISTS);
        }
        // 判断文章是否属于该用户
        if (article.getUserId() != user.getId()) {
            //文章不属于该用户
            log.warn(ResultCode.FAILED_FORBIDDEN.toString());
            return AppResult.failed(ResultCode.FAILED_FORBIDDEN);
        }
        // 删除文章
        articleService.deleteById(id);
        return AppResult.success(ResultCode.FAILED) ;
    }

    /**
     * 返回用户的文章列表
     * @param request
     * @param userId
     * @return
     */
    @ApiOperation("返回指定用户的文章列表")
    @GetMapping("/getAllByUserId")
    public  AppResult<List<Article>> getAllByUserId(
            HttpServletRequest request,
            @ApiParam("用户id") @RequestParam(value = "userId" ,required = false) Long userId) {
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        if (userId == null) {
            userId = user.getId();
        }
        List<Article> articles = articleService.selectByUserId(userId);
        return AppResult.success(articles);
    }


}
